package com.lcz.mytest.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v4.view.PagerTabStrip;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.SearchView;
import android.text.Html;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.SpinnerAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.lcz.mytest.R;
import com.lcz.mytest.adapter.FragmentAdapter;
import com.lcz.mytest.fragment.CollectFragment;
import com.lcz.mytest.utils.SharedPrefsUtil;
import com.lcz.mytest.widget.ToolBarActivity;


public class MainActivity extends ToolBarActivity implements ActionBar.OnNavigationListener, SearchView.OnQueryTextListener {
    private DrawerLayout mDrawerLayout;//侧滑页面
    private ActionBarDrawerToggle mDrawerToggle;
    private ViewPager mViewPager;
    private PagerTabStrip pager_tab_strip;// 菜单页面滑动
    private LinearLayout user_info;//登录用户的显示
    private TextView username;//用户名
    private TextView exit;//退出
    private LinearLayout ll_login;//登录按钮
    private FrameLayout fl_menu;//侧滑页面菜单
    private View view;
    private String type;//图表显示类型
    private SearchView searchView;//搜索单个股票代码
    public static boolean isLogin = false;
    public static String USERNAME;
    private RelativeLayout collect;

    public void setType(String type) {
        this.type = type;
    }

    public String getType() {
        return type;
    }

    @Override
    protected void findViewById() {
        setContentView(R.layout.activity_main);
        super.findViewById();
        mDrawerLayout = (DrawerLayout) findViewById(R.id.dl);
        mViewPager = (ViewPager) findViewById(R.id.vp);
        pager_tab_strip = (PagerTabStrip) findViewById(R.id.pager_tab_strip);
        view = View.inflate(MainActivity.this, R.layout.drawlayout_login, null);
        if (view != null) {
            user_info = (LinearLayout) view.findViewById(R.id.ll_user_info);
            username = (TextView) view.findViewById(R.id.tv_username);
            exit = (TextView) view.findViewById(R.id.tv_exit);
            ll_login = (LinearLayout) view.findViewById(R.id.ll_login);
            collect = (RelativeLayout) findViewById(R.id.collect);
            fl_menu = (FrameLayout) findViewById(R.id.fl_menu);
            fl_menu.addView(view);
        }
    }

    @Override
    protected void initView() {
        super.initView();
        this.setTitle("首页");
        // 生成一个SpinnerAdapter
        SpinnerAdapter adapter = ArrayAdapter.createFromResource(this, R.array.type, android.R.layout.simple_spinner_dropdown_item);
        // 将ActionBar的操作模型设置为NAVIGATION_MODE_LIST
        getSupportActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
        // 为ActionBar设置下拉菜单和监听器
        getSupportActionBar().setListNavigationCallbacks(adapter, this);
        // 打开toolbar返回开关
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        // DrawerLayout、ActionBarDrawerToggle 关联toolbar
        mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, toolbar, R.string.drawer_open, R.string.drawer_close);
        mDrawerToggle.syncState();
        mDrawerLayout.setDrawerListener(mDrawerToggle);
        // 设置标签下划线的颜色
        pager_tab_strip.setTabIndicatorColor(getResources().getColor(R.color.indicatorcolor));

        // 登陆
        view.findViewById(R.id.bt_login).setOnClickListener(
                new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(MainActivity.this, LoginActivity.class);
                        startActivityForResult(intent, 100);
                    }
                });
        // 注册
        view.findViewById(R.id.bt_regist).setOnClickListener(
                new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(MainActivity.this,
                                RegistersActivity.class);
//                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        startActivityForResult(intent, 200);
                    }
                });

        view.findViewById(R.id.collect).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this,
                        CollectActivity.class);
                startActivityForResult(intent, 200);
            }
        });

        //条目名称
        String[] tab_names = this.getResources().getStringArray(R.array.tab_names);
        mViewPager.setAdapter(new FragmentAdapter(getSupportFragmentManager(), tab_names));
        String name = SharedPrefsUtil.getValue(this, "username", "");
        if (name.equals("")) {
            isLogin = false;
            USERNAME = "";
            ll_login.setVisibility(View.VISIBLE);
            user_info.setVisibility(View.GONE);
        } else {
            isLogin = true;
            USERNAME = name;
            ll_login.setVisibility(View.GONE);
            user_info.setVisibility(View.VISIBLE);
            username.setText("用户名：" + name);
        }
        exit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isLogin = false;
                SharedPrefsUtil.clearValue(MainActivity.this);
                username.setText("");
                //发送广播刷新收藏页面
                sendBroadcast(new Intent().setAction(CollectFragment.RECEIVER_INFILTER).putExtra("login", false));
                ll_login.setVisibility(View.VISIBLE);
                user_info.setVisibility(View.GONE);
            }
        });
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        searchView = (SearchView) menu.findItem(R.id.action_search).getActionView();
//        需要先实现onQueryTextSubmit()、onQueryTextChange()才能进行监听
        searchView.setQueryHint(Html.fromHtml("<font color = #a6a3a3>" + "请输入sh/sz开头的代码" + "</font>"));
        searchView.setOnQueryTextListener(this);// 搜索的监听
        return true;
    }

    /**
     * 处理ToolBar菜单条目的点击事件
     */
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_search:
                Toast.makeText(getApplicationContext(), "搜索", Toast.LENGTH_SHORT).show();
                break;
        }
        return mDrawerToggle.onOptionsItemSelected(item) | super.onOptionsItemSelected(item);
    }

    // 当搜索提交的时候
    @Override
    public boolean onQueryTextSubmit(String query) {

//        if (query.startsWith("sh60") || query.startsWith("sz000")) {
        if (query.matches("^sh60[0,1]\\d{3}") || query.matches("^sz000\\d{3}")) {
//            Toast.makeText(getApplicationContext(), query, Toast.LENGTH_SHORT).show();
            if (getType().equals("历史数据")) {
                Intent intent = new Intent(this, PastStockChartActivity.class);
                intent.putExtra("query", query);
                startActivityForResult(intent, 300);
            } else if (getType().equals("实时数据")) {
                Intent intent = new Intent(this, PresentStockChartActivity.class);
                intent.putExtra("query", query);
                startActivityForResult(intent, 300);
            }
        } else {
            Toast.makeText(getApplicationContext(), "搜索内容暂不存在，请重新输入", Toast.LENGTH_SHORT).show();
            searchView.setQuery("", false);
        }
        return true;
    }

    //文本发生变化
    @Override
    public boolean onQueryTextChange(String newText) {
        return false;
    }


    //退出程序
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            new AlertDialog.Builder(this)
                    .setTitle("提示")
                    .setMessage("关闭应用程序")
                    .setPositiveButton("确定",
                            new DialogInterface.OnClickListener() {

                                @Override
                                public void onClick(DialogInterface dialog,
                                                    int which) {
                                    if (!SharedPrefsUtil.getValue(MainActivity.this, "isRemember", false)) {
                                        SharedPrefsUtil.clearValue(MainActivity.this);
                                    }
                                    new BaseActivity().killAll();
                                }

                            }).setNegativeButton("取消", null).show();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == 100 || requestCode == 200) {
                String name = SharedPrefsUtil.getValue(this, "username", "");
                if (name != null || !name.equals("")) {
                    isLogin = true;
                    ll_login.setVisibility(View.GONE);
                    user_info.setVisibility(View.VISIBLE);
                    username.setText(name);
                } else {
                    isLogin = false;
                    ll_login.setVisibility(View.VISIBLE);
                    user_info.setVisibility(View.GONE);
                }
            }
            if (requestCode == 300) {
                // 生成一个SpinnerAdapter
                SpinnerAdapter adapter = ArrayAdapter.createFromResource(this, R.array.type, android.R.layout.simple_spinner_dropdown_item);
                // 将ActionBar的操作模型设置为NAVIGATION_MODE_LIST
                getSupportActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
                // 为ActionBar设置下拉菜单和监听器
                getSupportActionBar().setListNavigationCallbacks(adapter, this);
            }
        }
    }

    @Override
    public boolean onNavigationItemSelected(int itemPosition, long itemId) {
        String[] listNames = getResources().getStringArray(R.array.type);
        Toast.makeText(getApplicationContext(), listNames[itemPosition] + itemPosition, Toast.LENGTH_SHORT).show();
        if (itemPosition == 2) {//多条件查询
            Intent intent = new Intent(MainActivity.this, SeachActivity.class);
            startActivityForResult(intent, 300);
        } else {
            setType(listNames[itemPosition]);
        }
        return true;
    }

}
